package com.fsh.lingsp.common.user.dao;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fsh.lingsp.common.user.domain.entity.UserApply;
import com.fsh.lingsp.common.user.domain.enums.ApplyReadStatusEnum;
import com.fsh.lingsp.common.user.domain.enums.ApplyStatusEnum;
import com.fsh.lingsp.common.user.domain.enums.ApplyTypeEnum;
import com.fsh.lingsp.common.user.mapper.UserApplyMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户申请表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-03-08
 */
@Service
public class UserApplyDao extends ServiceImpl<UserApplyMapper, UserApply> {

    /**
     * 普通翻页 获取好友申请列表
     */
    public IPage<UserApply> friendApplyPage(Long uid, Page plusPage) {
        return lambdaQuery()
                .eq(UserApply::getTargetId,uid)
                .eq(UserApply::getType, ApplyTypeEnum.ADD_FRIEND.getCode())
                .orderByDesc(UserApply::getCreateTime)
                .page(plusPage);
    }

    /**
     * @param uid    UID
     * @param applyIds ID 申请列表，纯id
     *
     *  将申请列表设为已读
     */
    public void readAlready(Long uid, List<Long> applyIds) {
        lambdaUpdate()
                .eq(UserApply::getTargetId,uid)
                .eq(UserApply::getReadStatus, ApplyReadStatusEnum.UNREAD.getCode())
                .set(UserApply::getReadStatus,ApplyReadStatusEnum.READ.getCode())
                .in(UserApply::getId,applyIds)
                .update();
    }

    /**
     * 查询当前用户申请列表的未读数
     */
    public Integer getUnReadCount(Long uid) {
        return lambdaQuery()
                .eq(UserApply::getTargetId,uid)
                .eq(UserApply::getReadStatus,ApplyReadStatusEnum.UNREAD.getCode())
                .count();
    }

    /**
     * 同意好友申请，就是更新一个字段
     *
     * @param applyId 申请记录的主键id
     */
    public void agree(Long applyId) {
        lambdaUpdate()
                .eq(UserApply::getId,applyId)
                .set(UserApply::getStatus, ApplyStatusEnum.AGREE.getStatus())
                .update();
    }

    /**
     * 查询 自己的待审批记录。（向别人申请好友请求，但是还没同意，仍处在待审批状态）
     */
    public UserApply getFriendApproving(Long uid, Long targetUid) {
        return lambdaQuery()
                .eq(UserApply::getUid,uid)
                .eq(UserApply::getTargetId,targetUid)
                .eq(UserApply::getType,ApplyTypeEnum.ADD_FRIEND.getCode())
                .eq(UserApply::getStatus,ApplyStatusEnum.WAIT_APPROVAL.getStatus())
                .one();
    }
}
